package org.jeecg.modules.wlhy.hyvehicle.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.constant.enums.ExamineStatusEnum;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.ExcelUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.constant.UserTypeEnum;
import org.jeecg.modules.third.digitalseal.service.DigitalSignetService;
import org.jeecg.modules.third.digitalseal.utils.ImageBase64Util;
import org.jeecg.modules.wlhy.captain.entity.HyCaptain;
import org.jeecg.modules.wlhy.captain.entity.HyCaptainVehicle;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainService;
import org.jeecg.modules.wlhy.captain.service.IHyCaptainVehicleService;
import org.jeecg.modules.wlhy.company.entity.HyCompanyConfig;
import org.jeecg.modules.wlhy.company.service.IHyCompanyConfigService;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyevent.event.PicDownloadEvent;
import org.jeecg.modules.wlhy.hyvehicle.entity.*;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyDriverVehicleService;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hyzyb.entity.HyZybStatus;
import org.jeecg.modules.wlhy.hyzyb.service.IHyZybService;
import org.jeecg.modules.wlhy.report.IReportService;
import org.jeecg.modules.wlhy.report.OrdosReportService;
import org.jeecg.modules.wlhy.report.ReportServiceFactory;
import org.jeecg.modules.wlhy.report.impl.*;
import org.jeecg.modules.wlhy.setting.entity.HySetting;
import org.jeecg.modules.wlhy.setting.service.IHySettingService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.UserUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 车辆管理
 * @Author: duanlikao
 * @Date:   2020-12-05
 * @Version: V1.0
 */
@Api(tags="车辆管理")
@RestController
@RequestMapping("/hyVehicle/hyVehicle")
//@RequiresRoles(value={"admin", "customer", "driver"},logical = Logical.OR)
@Slf4j
public class HyVehicleController extends JeecgController<HyVehicle, IHyVehicleService> {

	@Autowired
	private IHyVehicleService hyVehicleService;

    @Resource
    private BaseCommonService baseCommonService;

	@Autowired
	private IHyDriverService hyDriverService;

	@Autowired
	private IHyDriverVehicleService hyDriverVehicleService;

	@Autowired
	private TjJgReportService tjJgReportService;

	@Autowired
	private DigitalSignetService digitalSignetService;

	@Autowired
	private IHyDriverVehicleService driverVehicleService;

	@Resource
	private HbReportService hbReportService;

	@Resource
	private HenanReportService hnReportService;

	@Autowired
	private LiaoNingReportService liaoNingReportService;

	@Resource
	private YunnanReportService yunnanReportService;

	@Resource
	private SxiReportService sxiReportService;

	@Resource
	private CqReportService cqReportService;

	@Resource
	private OrdosReportService ordosReportService;

	@Resource
	private AhReportService ahReportService;

	@Resource
	private JsuReportService jsuReportService;

	@Resource
	private JsuV2ReportService jsuV2ReportService;

	@Resource
	private XinjiangReportService xjReportService;

	@Resource
	private NxReportService nxReportService;

	@Resource
	private NmgReportService nmgReportService;

	@Resource
	private HuaibeiReportService huaibeiReportService;

	@Resource
	private JxiReportService jxiReportService;

	@Resource
	private YuanqvReportService yuanqvReportService;

	@Resource
	private ZjiaoReportService zjiaoReportService;

	@Autowired
	private IHyZybService hyZybService;

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	@Autowired
	private UserUtil userUtil;


	@Autowired
	private IHyShippingNoteService shippingNoteService;

	@Autowired
	private IHyCompanyConfigService companyConfigService;

	@Autowired
	private IHySettingService settingService;

	@Autowired
	private IHyCaptainService captainService;
	@Autowired
	private IHyCaptainVehicleService captainVehicleService;



	/**
	 * 分页列表查询
	 *
	 * @param hyVehicle
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="车辆管理-分页列表查询", notes="车辆管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(HyVehicleDTO hyVehicle,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

		QueryWrapper<HyVehicle> queryWrapper = new QueryWrapper<>();
		List<String> ids = new ArrayList <>();
		String vehicleNumber = hyVehicle.getVehicleNumber();
		if (StringUtils.isNotBlank(vehicleNumber)){
			queryWrapper.like("vehicle_number",vehicleNumber.trim());
			hyVehicle.setVehicleNumber("");
		}
		//新增智运宝设备号查询
		if (StrUtil.isNotEmpty(hyVehicle.getVehicleDevice())) {
			queryWrapper.like("vehicle_device", hyVehicle.getVehicleDevice());
			hyVehicle.setVehicleDevice("");
		}
		//如果是承运商只查询承运商的车辆
		if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
			String id = userUtil.getLoginUser().getId();
			HyCaptain captain = captainService.getInfoByUserId(id);
			if (captain!=null){
				queryWrapper.eq("carrier_id",captain.getId());
			}else {
				return Result.error("承运商列表中没有该用户");
			}

		}else if (StringUtils.isNotEmpty(hyVehicle.getCarrierName())) {
			//根据承运商id获取绑定车辆绑定的司机
			HyCaptain captain = captainService.getOne(new LambdaQueryWrapper<HyCaptain>().like(HyCaptain::getCaptainName, hyVehicle.getCarrierName()));
			if (captain==null){
				return Result.ok();
			}
			List<HyCaptainVehicle> carriers = captainVehicleService.list(new QueryWrapper<HyCaptainVehicle>().eq("captain_id", captain.getId()));
			//根据关联表获取绑定的车辆信息
			List<String> vehicleIdList = carriers.stream().map(HyCaptainVehicle::getVehicleId).collect(Collectors.toList());
			//获取的司机数据为承运商添加的司机及承运商所属车辆绑定的司机
			if (vehicleIdList.size()!=0){
				ids.addAll(vehicleIdList);
			}
		}
		String driverId =  StringUtils.isNotEmpty(hyVehicle.getDriverId()) ?  hyVehicle.getDriverId() : StringUtils.EMPTY;
		if(StringUtils.isNotEmpty(driverId)){
			ids.addAll(hyDriverVehicleService.getVehicleIdListByDriverId(driverId) );
		}
		hyVehicle.setDriverId("");

		queryWrapper.eq("del_flag", 0);
		HyVehicle v = new HyVehicle();
		//把dto对象中的属性值复制到vo对象中
		BeanUtils.copyProperties(hyVehicle, v);
		QueryGenerator.initQueryWrapper(queryWrapper, v, req.getParameterMap());
		Page<HyVehicle> page = new Page<HyVehicle>(pageNo, pageSize);

		if(CollectionUtils.isNotEmpty(ids) ){
			queryWrapper.in("v.id",ids);
		}else{
			if(StringUtils.isNotEmpty(driverId)  ){
				return Result.OK();
			}
		}

		//如果查询上报状态的数据，需要查询任意一个省监管平台
		if (StrUtil.isNotEmpty(hyVehicle.getUploadStatus())) {
			queryWrapper.and(wrapper->{
				wrapper.eq("upload_status", hyVehicle.getUploadStatus()).or()
						.eq("sx_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("hb_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("ah_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("js_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("xz_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("zj_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("sd_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("hubei_upload_status", hyVehicle.getUploadStatus()).or()
						.eq("jx_upload_status", hyVehicle.getUploadStatus())
				;
			});

			hyVehicle.setUploadStatus("");
		}

//		IPage<HyVehicle> pageList = hyVehicleService.page(page, queryWrapper);
		IPage<HyVehicle> pageList = hyVehicleService.pageList(page, queryWrapper,userUtil.getCustomerById());
		//IPage<HyVehicle> pageList = hyVehicleService.pageList1(page, queryWrapper,userUtil.getCustomerById());

		pageList.getRecords().forEach(hyVehicle1 -> {
			//根据车辆id获取所绑定的承运商
			HyCaptainVehicle hyCaptainVehicle = captainVehicleService.getOne(new QueryWrapper<HyCaptainVehicle>().eq("vehicle_id", hyVehicle1.getId()));
			if (hyCaptainVehicle!=null){
				hyVehicle1.setCarrierId(hyCaptainVehicle.getCaptainId());
			}
		});
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hyVehicle
	 * @return
	 */
	@AutoLog(value = "车辆管理-添加")
	@ApiOperation(value="车辆管理-添加", notes="车辆管理-添加")
	@PostMapping(value = "/add")
	@RequiresPermissions("sys:vehicle:add")
	public Result<?> add(@RequestBody  HyVehicle hyVehicle) {
		hyVehicle.setExamineStatus(ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
		hyVehicle.setExamineType("1");
		hyVehicle.setExamineDate( new Date());
		hyVehicle.setBusinessLicense(oConvertUtils.getNumberFromString(hyVehicle.getBusinessLicense()));
		return hyVehicleService.saveHyVehicle(hyVehicle);
	}

	/**
	 *  编辑
	 *
	 * @param hyVehicle
	 * @return
	 */
	@AutoLog(value = "车辆管理-编辑")
	@ApiOperation(value="车辆管理-编辑", notes="车辆管理-编辑")
	@PutMapping(value = "/edit")
	@RequiresPermissions("sys:vehicle:edit")
	@CacheEvict(value = CacheConstant.SYS_DICT_TABLE_CACHE ,key = "'SimpleKey [hy_vehicle,vehicle_number,id,' + #hyVehicle.id + ']'")
	public Result<?> edit(@RequestBody HyVehicle hyVehicle) {
		String vehicleId = hyVehicle.getId() ;
		HyVehicle hyVehicleDb = hyVehicleService.getById(vehicleId);
		if(hyVehicleDb == null){
			return Result.OK("编辑信息不存在!");
		}
		if (StringUtils.isEmpty(hyVehicle.getDriverId()) ) {
			throw new JeecgBootException("车辆未绑定司机,请绑定司机");
		}
		HySetting setting = settingService.getByTag("vehicleImg_upload");
		if (setting.getData().equals("1")&&hyVehicle.getVehicleImg()==null||setting.getData().equals("1")&&hyVehicle.getVehicleImg().equals("")){
			return Result.error("人车合照不能为空");
		}
		HySetting setting1 = settingService.getByTag("vehicle_emission_settings");
		if (setting1.getData().equals("1")&&hyVehicle.getEnvironmentalCertificate()==null||setting1.getData().equals("1")&&hyVehicle.getEnvironmentalCertificate().equals("")){
			return Result.error("环保证书不能为空");
		}
		hyVehicle.setBusinessLicense(oConvertUtils.getNumberFromString(hyVehicle.getBusinessLicense()));
		if (hyVehicle.getCarrierId()!=null&&hyVehicle.getCarrierId()!=""){
			HyCaptain captain = captainService.getById(hyVehicle.getCarrierId());
			if (captain==null){
				return Result.error("承运商信息不存在");
			}
			HyCaptainVehicle hyCaptainVehicle = captainVehicleService.getOne(new QueryWrapper<HyCaptainVehicle>().eq("vehicle_id", vehicleId));
			if (hyCaptainVehicle==null){
				hyCaptainVehicle = new HyCaptainVehicle();
				hyCaptainVehicle.setVehicleId(vehicleId);
				hyCaptainVehicle.setCaptainId(hyVehicle.getCarrierId());
				captainVehicleService.save(hyCaptainVehicle);
			}else {
				hyCaptainVehicle.setCaptainId(hyVehicle.getCarrierId());
				captainVehicleService.updateById(hyCaptainVehicle);
			}
		}
		//如果修改车牌号，需要记录日志
		if (hyVehicle.getVehicleNumber()!=hyVehicleDb.getVehicleNumber()){
			baseCommonService.addLog("用户名: " +userUtil.getUser().getUsername() + ",修改车牌号信息保存成功！"+hyVehicle.getVehicleNumber(),
					CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_3, null);
		}
		hyVehicleService.updateById(hyVehicle);
		hyVehicleService.binding(hyVehicle.getDriverId(),  hyVehicle.getId()) ;
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "车辆管理-通过id删除")
	@ApiOperation(value="车辆管理-通过id删除", notes="车辆管理-通过id删除")
	@DeleteMapping(value = "/delete")
	@RequiresPermissions("sys:vehicle:delete")
	public Result<?> delete(@RequestParam(name="id", required = true) String id) {

		HyVehicle hyVehicle = hyVehicleService.getById(id);
		if (null == hyVehicle) {
			return Result.error("车辆信息不存在");
		}

		log.warn("删除车辆信息, {}", JSONUtil.toJsonStr(hyVehicle));
		//如果是承运商只更改车辆的关联承运商id，不会删除车
		if (userUtil.getLoginUser().getUType().equals(UserTypeEnum.承运商.getCode())){
			hyVehicle.setCarrierId("");
			hyVehicleService.updateById(hyVehicle);
			return Result.OK();
		}
		QueryWrapper<HyShippingNote> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("vehicle_id", id);
		int shippingNoteCount = this.shippingNoteService.count(queryWrapper);
		if (shippingNoteCount > 0) {
			return Result.error(hyVehicle.getVehicleNumber() + " 车辆已有业务数据,不允许删除");
		}

        baseCommonService.addLog("删除车辆动作: " + hyVehicle.getId() + " " + hyVehicle.getVehicleNumber(),
                CommonConstant.LOG_TYPE_1, null);
		hyVehicleService.deleteVehicleById(id);
		return Result.OK("删除成功!");
	}
//
//	/**
//	 *  批量删除
//	 *
//	 * @param ids
//	 * @return
//	 */
//	@AutoLog(value = "车辆管理-批量删除")
//	@ApiOperation(value="车辆管理-批量删除", notes="车辆管理-批量删除")
//	@DeleteMapping(value = "/deleteBatch")
//	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
//		List<String> listIds =  Arrays.asList(ids.split(","));
//		for(String id: listIds){
//			HyVehicle hyVehicle =  hyVehicleService.getById(id);
//			hyVehicle.setIzUsed("0");
//			hyVehicleService.updateById(hyVehicle);
//			hyDriverVehicleService.updateByVehicleId( id, "0" );
//		}
//		this.hyVehicleService.removeByIds(Arrays.asList(ids.split(",")));
//		return Result.OK("批量删除成功!");
//	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="车辆管理-通过id查询", notes="车辆管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		HyVehicle hyVehicle = hyVehicleService.getById(id);
		if(hyVehicle==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hyVehicle);
	}


	/**
	 * 通过车量number查询司机对象
	 *
	 * @param id
	 * @return
	 */
//	@AutoLog(value = "车辆管理-通过车量id查询司机对象")
	@ApiOperation(value="车辆管理-通过车量id查询司机对象", notes="车辆管理-通过车量id查询司机对象")
	@GetMapping(value = "/queryByVehicleNumber")
	public Result<?> queryByVehicleNumber(@RequestParam(name="id",required=true) String id) {
		List<String> driverIds = new ArrayList<>();
		List<HyDriver> HyDriverVehicles = new ArrayList<>();
		if (StringUtils.isNotEmpty(id)) {
			//根据车id查找司机id列表
			driverIds = hyDriverVehicleService.getDriverIdListByVehicleId(id);
			if (driverIds.size() == 0) {
				return Result.error("未找到绑定司机数据");
			}
			QueryWrapper<HyDriver> queryWrapper = new QueryWrapper();
			queryWrapper.in("id",driverIds);
			HyDriverVehicles = hyDriverService.list(queryWrapper);
			return Result.OK(HyDriverVehicles);
		}
		return Result.error("没有找到该车辆");
	}




    /**
    * 导出excel
    *
    * @param request
    * @param hyVehicle
    */
    @RequestMapping(value = "/exportXls")
	@RequiresPermissions("sys:vehicle:exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HyVehicle hyVehicle) {

		QueryWrapper<HyVehicle> queryWrapper = new QueryWrapper<>();
		String vehicleNumber = hyVehicle.getVehicleNumber();
		if (StringUtils.isNotBlank(vehicleNumber)){
			queryWrapper.like("vehicle_number",vehicleNumber.trim());
			hyVehicle.setVehicleNumber("");
		}

		List<String> ids = new ArrayList <>();
		String driverId = StringUtils.isNotEmpty(hyVehicle.getDriverId()) ? hyVehicle.getDriverId() : StringUtils.EMPTY;
		if(StringUtils.isNotEmpty(driverId)){
			ids.addAll(hyDriverVehicleService.getVehicleIdListByDriverId(driverId));
		}

		if (CollUtil.isNotEmpty(ids)) {
			queryWrapper.in("driver_id", ids);
			hyVehicle.setDriverId("");
		}

		queryWrapper.eq("del_flag", 0);
		QueryGenerator.initQueryWrapper(queryWrapper, hyVehicle, request.getParameterMap());

		List<HyVehicle> exportList = this.hyVehicleService.list(queryWrapper);
		String domianURL = request.getParameter("domianURL");
		if(StringUtils.isNotEmpty(domianURL)) {
			domianURL+="/";
			for (HyVehicle vehicle : exportList) {
				String drivingLicenseImg = vehicle.getDrivingLicenseImg();
				if(StringUtils.isNotEmpty(drivingLicenseImg)){
					vehicle.setDrivingLicenseImg(domianURL + drivingLicenseImg);
				}

				String drivingLicenseImg2 = vehicle.getDrivingLicenseImg2();
				if(StringUtils.isNotEmpty(drivingLicenseImg2)){
					vehicle.setDrivingLicenseImg2(domianURL + drivingLicenseImg2);
				}

				String roadTransportImg = vehicle.getRoadTransportImg();
				if(StringUtils.isNotEmpty(roadTransportImg)){
					vehicle.setRoadTransportImg(domianURL + roadTransportImg);
				}

				String roadTransportImg2 = vehicle.getRoadTransportImg2();
				if(StringUtils.isNotEmpty(roadTransportImg2)){
					vehicle.setRoadTransportImg2(domianURL + roadTransportImg2);
				}

				String affiliationAgreement = vehicle.getAffiliationAgreement();
				if(StringUtils.isNotEmpty(affiliationAgreement)){
					vehicle.setAffiliationAgreement(domianURL + affiliationAgreement);
				}

				String vehicleImg = vehicle.getVehicleImg();
				if(StringUtils.isNotEmpty(vehicleImg)){
					vehicle.setVehicleImg(domianURL + vehicleImg);
				}
			}
		}

		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "车辆列表"); //此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.CLASS, HyVehicle.class);
		ExportParams exportParams = new ExportParams();
		exportParams.setAddIndex(true);
		mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		//ModelAndView mv = super.exportXls(request, hyVehicle, HyVehicle.class, "车辆管理");

        return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@RequiresPermissions("sys:vehicle:importExcel")
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HyVehicle.class);
    }

	@AutoLog(value = "车辆管理-车辆审核")
	@ApiOperation(value="车辆管理-车辆审核", notes="车辆管理-车辆审核")
	@PutMapping(value = "/examine")
	@RequiresPermissions("sys:vehicle:examine")
	public Result<?> examine(@RequestBody HyVehicle hyVehicle) {

		HyVehicle hyVehicleDb = hyVehicleService.getById(hyVehicle.getId());
		if(hyVehicleDb == null) {
			return Result.error("未找到对应数据");
		}

		if(!ExamineStatusEnum.isValid(hyVehicle.getExamineStatus())){
			return Result.error("审核状态不正确!");
		}
		hyVehicle.setId(hyVehicle.getId());
		hyVehicle.setExamineStatus(hyVehicle.getExamineStatus());
		hyVehicle.setExamineType("1");
		hyVehicle.setExamineDate(new Date());
		hyVehicle.setExaminRemark(hyVehicle.getExaminRemark());
		hyVehicleService.updateById(hyVehicle);

//		QueryWrapper <HyDriverVehicle> queryWrapper = new QueryWrapper();
//		queryWrapper.eq("vehicle_id", hyVehicle.getId());
//		queryWrapper.eq("iz_used",1);
//		queryWrapper.eq("del_flag",0);
//		List <HyDriverVehicle> listDriverVehicle = hyDriverVehicleService.list(queryWrapper);
//		List <String>  driverIdList =   CollectionUtils.isNotEmpty(listDriverVehicle)  ?
//				listDriverVehicle.stream().map(HyDriverVehicle::getDriverId).collect(Collectors.toList())
//				: new ArrayList <>();
//		List <HyDriver> hyDrivers = new ArrayList <>();
//		if(CollectionUtils.isNotEmpty(driverIdList)){
//			QueryWrapper<HyDriver> queryDriverWrapper = new QueryWrapper();
//			queryDriverWrapper.in("id",driverIdList);
//			hyDrivers = hyDriverService.list(queryDriverWrapper);
//		}
//
//		if(CollectionUtils.isNotEmpty(hyDrivers) )  {
//			LoginUser loginUser = UserUtil.getLoginUser();
//			for(HyDriver hyDriver :hyDrivers){
//				HyWarningMessage hyWarningMessage = new HyWarningMessage();
//				hyWarningMessage.setObjectId(hyVehicle.getId());
//				hyWarningMessage.setUserId(hyDriver.getUserId());
//				hyWarningMessage.setMessageType(MessageTypeEnum.MESSAGE_TYPE_CLSH.getCode());
//				hyWarningMessage.setMessageContent(
//						"司机 :"+hyDriver.getDriverName()+" 车辆信息: "+hyVehicleDb.getVehicleNumber()+" 已审核通过 !"
//				);
//				hyWarningMessage.setCreateBy(loginUser.getUsername());
//				hyWarningMessage.setCreateTime(new Date());
//				hyWarningMessageService.saveWarningMessage(hyWarningMessage);
//			}
//		}
		return Result.OK("审核成功!");
	}


	@AutoLog(value = "车辆上报")
	@ApiOperation(value = "车辆上报", notes = "车辆上报")
	@PutMapping(value = "/uploadVehicle")
	public Result<?> uploadVehicle(@RequestBody HyVehicleDTO hyVehicle) {

		if (StrUtil.isEmpty(hyVehicle.getCompanyId())) {
			return Result.error("未选择分公司");
		}

		//申报公司
		HyCompanyConfig companyConfig = companyConfigService.getOne(new QueryWrapper<HyCompanyConfig>()
				.eq("company_id", hyVehicle.getCompanyId()
				));

		if (companyConfig == null) {
			throw new JeecgBootException("上报公司配置信息不存在");
		}

		log.warn("按公司上报司机，{}", JSONUtil.toJsonStr(companyConfig));
		//hyShippingNoteDb.setCompanyId(hyShippingNoteDb.getCompanyId());
		//在getReport中做判断 如果report==null，抛异常
		IReportService reportService = ReportServiceFactory.getReport(companyConfig.getReportPlatformType());
		reportService.checkReport();
		reportService.setReportInfo(companyConfig);
		return reportService.reportVehicle(hyVehicle.getId(), hyVehicle.getCompanyId());
	}


//	@AutoLog(value = "中交中间件车辆上报")
//	@ApiOperation(value="中交中间件车辆上报", notes="中交中间件车辆上报")
//	@PutMapping(value = "/zjupload")
//	public Result<?> zjupload(@RequestBody HyVehicle hyVehicle) {
//		return zjiaoReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//	@AutoLog(value = "河南车辆上报")
//	@ApiOperation(value="河南车辆上报", notes="河南车辆上报")
//	@PutMapping(value = "/hnupload")
//	public Result<?> hnupload(@RequestBody HyVehicle hyVehicle) {
//		return this.hnReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//	@AutoLog(value = "车辆管理-天津车辆上报")
//	@ApiOperation(value="车辆管理-天津车辆上报", notes="车辆管理-天津车辆上报")
//	@PutMapping(value = "/upload")
//	@RequiresPermissions("sys:vehicle:upload")
//	public Result<?> upload(@RequestBody HyVehicle hyVehicle) {
//    	return this.tjJgReportService.uploadVehicle(hyVehicle.getId());
//
//	}
//
//	@AutoLog(value = "车辆管理-河北车辆上报")
//	@ApiOperation(value="车辆管理-河北车辆上报", notes="车辆管理-河北车辆上报")
//	@PutMapping(value = "/hbupload")
//	@RequiresPermissions("sys:vehicle:hbupload")
//	public Result<?> hbupload(@RequestBody HyVehicle hyVehicle) {
//		return hbReportService.uploadVehicle(hyVehicle.getId());
//
//	}
//
//	@AutoLog(value = "车辆管理-辽宁车辆上报")
//	@ApiOperation(value="车辆管理-辽宁车辆上报", notes="车辆管理-辽宁车辆上报")
//	@PutMapping(value = "/lnupload")
//	@RequiresPermissions("sys:vehicle:lnupload")
//	public Result<?> lnupload(@RequestBody HyVehicle hyVehicle) {
//		return liaoNingReportService.uploadVehicle(hyVehicle.getId());
//
//	}
//
//	@AutoLog(value = "车辆管理-云南车辆上报")
//	@ApiOperation(value="车辆管理-辽宁车辆上报", notes="车辆管理-辽宁车辆上报")
//	@PutMapping(value = "/ynupload")
//	@RequiresPermissions("sys:vehicle:ynupload")
//	public Result<?> ynupload(@RequestBody HyVehicle hyVehicle) {
//		return this.yunnanReportService.uploadVehicle(hyVehicle.getId());
//
//	}
//
//	@AutoLog(value = "车辆管理-山西车辆上报")
//	@ApiOperation(value="车辆管理-山西车辆上报", notes="车辆管理-山西车辆上报")
//	@PutMapping(value = "/sxupload")
//	@RequiresPermissions("sys:vehicle:sxupload")
//	public Result<?> sxupload(@RequestBody HyVehicle hyVehicle) {
//		return this.sxiReportService.uploadVehicle(hyVehicle.getId());
//
//	}

//	@AutoLog(value = "车辆管理-安徽车辆上报")
//	@ApiOperation(value="车辆管理-安徽车辆上报", notes="车辆管理-安徽车辆上报")
//	@PutMapping(value = "/ahupload")
//	public Result<?> ahupload(@RequestBody HyVehicle hyVehicle) {
//		return this.ahReportService.uploadVehicle(hyVehicle.getId());
//	}

//	@AutoLog(value = "车辆管理-江苏车辆上报")
//	@ApiOperation(value="车辆管理-江苏车辆上报", notes="车辆管理-江苏车辆上报")
//	@PutMapping(value = "/jsupload")
//	public Result<?> jsupload(@RequestBody HyVehicle hyVehicle) {
//		return this.jsuReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//	@AutoLog(value = "车辆管理-江苏V2车辆上报")
//	@ApiOperation(value="车辆管理-江苏V2车辆上报", notes="车辆管理-江苏V2车辆上报")
//	@PutMapping(value = "/jsv2upload")
//	public Result<?> jsv2upload(@RequestBody HyVehicle hyVehicle) {
//		return this.jsuV2ReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//
//
//	@AutoLog(value = "车辆管理-新疆车辆上报")
//	@ApiOperation(value="车辆管理-新疆车辆上报", notes="车辆管理-新疆车辆上报")
//	@PutMapping(value = "/xjupload")
//	@RequiresPermissions("sys:vehicle:xjupload")
//	public Result<?> xjupload(@RequestBody HyVehicle hyVehicle) {
//		return this.xjReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//	@AutoLog(value = "车辆管理-宁夏车辆上报")
//	@ApiOperation(value="车辆管理-宁夏车辆上报", notes="车辆管理-宁夏车辆上报")
//	@PutMapping(value = "/nxupload")
//	public Result<?> nxupload(@RequestBody HyVehicle hyVehicle) {
//		return this.nxReportService.uploadVehicle(hyVehicle.getId());
//	}
//
//	@AutoLog(value = "车辆管理-内蒙古车辆上报")
//	@ApiOperation(value="车辆管理-内蒙古车辆上报", notes="车辆管理-内蒙古车辆上报")
//	@PutMapping(value = "/nmgupload")
//	public Result<?> nmgupload(@RequestBody HyVehicle hyVehicle) {
//		return this.nmgReportService.uploadVehicle(hyVehicle.getId());
//	}

	@AutoLog(value = "车辆管理-淮北车辆上报")
	@ApiOperation(value="车辆管理-淮北车辆上报", notes="车辆管理-淮北车辆上报")
	@PutMapping(value = "/huaibeiupload")
	public Result<?> huaibeiupload(@RequestBody HyVehicle hyVehicle) {
		return this.huaibeiReportService.uploadVehicle(hyVehicle.getId());
	}

	@AutoLog(value = "车辆管理-园区车辆上报")
	@ApiOperation(value="车辆管理-园区车辆上报", notes="车辆管理-园区车辆上报")
	@PutMapping(value = "/yqupload")
	public Result<?> yqupload(@RequestBody HyVehicle hyVehicle) {
		return this.yuanqvReportService.uploadVehicle(hyVehicle.getId());
	}

//	@AutoLog(value = "江西车辆上报")
//	@ApiOperation(value = "江西车辆上报", notes = "江西车辆上报")
//	@PutMapping(value = "/jxupload")
//	public Result<?> jxupload(@RequestBody HyVehicle hyVehicle) {
//		return this.jxiReportService.uploadVehicle(hyVehicle.getId());
//	}
//
	@AutoLog(value = "ordos车辆上报")
	@ApiOperation(value = "ordos车辆上报", notes = "ordos车辆上报")
	@PutMapping(value = "/ordosupload")
	public Result<?> ordosupload(@RequestBody HyVehicle hyVehicle) {
		return this.ordosReportService.reportVehicle(hyVehicle.getId(), "3000");
	}

	/**
	 * 起草车辆挂靠声明
	 */
	@AutoLog(value = "APP电子签章-起草车辆挂靠声明")
	@ApiOperation(value="APP电子签章-起草车辆挂靠声明", notes="APP电子签章-起草车辆挂靠声明")
	@PostMapping(value = "/draftVehicleHang")
	public Result<?> draftVehicleHang(@RequestBody HyVehicle hyVehicle) {

		String driverId = hyVehicle.getDriverId();
		if(StringUtils.isBlank(hyVehicle.getDriverId()) ){
			List<HyDriverVehicle> hyDriverVehicles  = driverVehicleService.getInfoByVehicleId(hyVehicle.getId());

			if(CollectionUtils.isEmpty(hyDriverVehicles) ){
				return Result.error("查询不到此车辆对应的司机信息");
			}
			driverId = hyDriverVehicles.get(0).getDriverId();
		}

		//拿到司机数据
		HyDriver driver = hyDriverService.getById(driverId);
		//拿到司机数据
		if(driver == null){
			return Result.error("司机表中["+driverId+"]司机信息不存在!");
		}
		//车牌号
		String vehicleNumber = hyVehicle.getVehicleNumber();
		//运输公司
		String companyName = hyVehicle.getOwner();

		if(vehicleNumber == null || StringUtils.isEmpty(vehicleNumber)){
			return Result.error("无车牌号信息！");
		}
		if(companyName == null || StringUtils.isEmpty(companyName)){
			return Result.error("无车辆所有人信息！");
		}
		String contractPath = digitalSignetService.draftVehicleContract(driver, vehicleNumber, companyName);
		if(contractPath == null){
			return Result.error("未获取到合同地址");
		}
		if(contractPath.equals("")){
			return Result.error("未获取到正确的合同模板地址！");
		}
		return Result.OK(contractPath);
	}

	/**
	 * 验证车辆是否入网，车牌号_颜色
	 */
	@PostMapping(value = "/checkTruckExist")
	public Result<?> checkTruckExist(@RequestBody HyVehicle hyVehicle){
		if (StrUtil.isEmpty(hyVehicle.getVehicleNumber()) || StrUtil.isEmpty(hyVehicle.getVehiclePlateColorCode())) {
			return Result.error("查询参数不正确");
		}

		return this.hyVehicleService.checkVehicleNumber(hyVehicle);
	}


	/**
	 * 车辆挂靠声明添加司机签章
	 */
	@AutoLog(value = "APP电子签章-车辆挂靠声明添加司机签章")
	@ApiOperation(value="APP电子签章-车辆挂靠声明添加司机签章", notes="APP电子签章-车辆挂靠声明添加司机签章")
	@PostMapping(value = "/addSignet")
	public Result<?> addSignet(@RequestBody JSONObject jsonObject){
		String filePath = jsonObject.getString("filePath");
		String signetBase64 = jsonObject.getString("signetBase64");
		log.debug("[车辆挂靠声明添加司机签章] 声明地址：{}", filePath);
		//log.debug("[车辆挂靠声明添加司机签章] 签章base64：{}", signetBase64);
		if(filePath == null || StringUtils.isEmpty(filePath)){
			return Result.error("合同地址错误！");
		}
		if(signetBase64 == null || StringUtils.isEmpty(signetBase64)){
			return Result.error("签名图片Base64码错误！");
		}
		String signetPath = "documents" + File.separator  +  DateUtils.getDate("yyyyMMdd")+ File.separator + "司机签名_" + DateUtils.getDate("yyyyMMddHHmmss") + ".png";
		String signetWholePath = uploadpath + File.separator + signetPath;
		log.debug("[车辆挂靠声明添加司机签章]signetPath：{}", signetPath);
		boolean toImg = ImageBase64Util.base64StringToImage(signetBase64, signetWholePath);
		if(toImg == false) {
			return Result.error("base64转图片失败！");
		}
		return digitalSignetService.addSignetForVehicle(filePath, signetPath);
	}

	@AutoLog(value = "道达上报")
	@ApiOperation(value="道达上报", notes="道达上报")
	@PutMapping(value = "/daodaUpload")
	public Result<?> daodaUpload(@RequestBody HyVehicle hyVehicle) {
		return hyVehicleService.uploadDaoda(hyVehicle) ? Result.OK("上报成功!") : Result.error("上报失败!");
	}

	@AutoLog(value = "辽宁税务上报车辆信息")
	@ApiOperation(value="辽宁税务上报车辆信息", notes="辽宁税务上报车辆信息")
	@PutMapping(value = "/lnTaxUploadVehicle")
	public Result<?> lnTaxUploadVehicle(@RequestBody HyVehicle hyVehicle){
		return hyVehicleService.lnTaxUploadVehicle(hyVehicle);
	}

	@AutoLog(value = "辽宁税务更新车辆信息")
	@PutMapping(value = "/updatelnTaxUploadVehicle")
	public Result<?> updatelnTaxUploadVehicle(@RequestBody HyVehicle hyVehicle){
		return hyVehicleService.updatelnTaxUploadVehicle(hyVehicle);
	}

	@AutoLog(value = "辽宁税务上报车辆照片")
	@ApiOperation(value="辽宁税务上报车辆照片", notes="辽宁税务上报车辆照片")
	@PutMapping(value = "/lnTaxUploadVehicleImg")
	public Result<?> lnTaxUploadVehicleImg(@RequestBody JSONObject jsonObject){
		JSONObject vehicleO = jsonObject.getJSONObject("vehicle");
		HyVehicle hyVehicle = vehicleO.toJavaObject(HyVehicle.class);
		int index = jsonObject.getInteger("index");
		return hyVehicleService.lnTaxUploadVehicleImg(hyVehicle, index);
	}
	@AutoLog(value = "辽宁税务上报车辆与司机绑定关系")
	@ApiOperation(value="辽宁税务上报车辆与司机绑定关系", notes="辽宁税务上报车辆与司机绑定关系")
	@PutMapping(value = "/lnTaxUploadVehicleDriver")
	public Result<?> lnTaxUploadVehicleDriver(@RequestBody HyVehicle hyVehicle){
		return hyVehicleService.lnTaxUploadVehicleDriver(hyVehicle);
	}
	@AutoLog(value = "辽宁税务上报车辆所有信息")
	@ApiOperation(value="辽宁税务上报车辆所有信息", notes="辽宁税务上报车辆所有信息")
	@PutMapping(value = "/lnTaxUploadVehicleAll")
	public Result<?> lnTaxUploadVehicleAll(@RequestBody HyVehicle hyVehicle){
		return hyVehicleService.lnTaxUploadVehicleAll(hyVehicle);
	}

	@AutoLog(value = "快货运上报车辆")
	@ApiOperation(value="快货运上报车辆", notes="快货运上报车辆")
	@PostMapping(value = "/tosUpload")
	public Result<?> tosUpload(@RequestBody HyVehicle hyVehicle){
		return hyVehicleService.tosUploadVehicle(hyVehicle);
	}


	/**
	 * 通过excel导入数据
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/importVehicle", method = RequestMethod.POST)
//	@RequiresPermissions("sys:vehicle:importExcel")
	public Result<?> importVehicle(HttpServletRequest request) throws InterruptedException {
		List<ImportHyVehiceDTO> list = ExcelUtil.importExcel(request, ImportHyVehiceDTO.class);
		if(CollectionUtils.isEmpty(list)) {
			return Result.error("导入数据不能为空！");
		}

		this.checkData(list);

		List<String> vehicleNumbers = list.stream().map(
				item -> item.getVehicleNumber().trim()
		).distinct().filter(Objects::nonNull).collect(Collectors.toList());


		int section = 10;
		List<HyVehicle> vehicleList = new LinkedList <>() ;
		for (int index = 0, end = 0; index < vehicleNumbers.size(); index = end) {
			end = (end + section) <= vehicleNumbers.size() ? end + section : vehicleNumbers.size();
			if (index < end) {
				QueryWrapper <HyVehicle> queryVehicleWrapper = new QueryWrapper();
				queryVehicleWrapper.in("vehicle_number" ,vehicleNumbers.subList(index, end));
				vehicleList.addAll(hyVehicleService.list(queryVehicleWrapper));
			}
		}

		if( vehicleList.size() > 0){
			List<String>  dbVehicleNumbers = vehicleList.stream().map(
					item -> item.getVehicleNumber()
			).collect(Collectors.toList());

			String filterVehicleNumbers = vehicleNumbers.stream()
					.filter(item -> dbVehicleNumbers.contains(item))
					.collect(Collectors.joining(",", "(", ")"));

			return Result.error(filterVehicleNumbers+"车辆数据信息已存在");
		}

		//Added at 2023-07-18 for 特殊车辆导入模板可以配置要上传的图片URL
		//根据图片URL下载图片
		int index = 1;
		for (ImportHyVehiceDTO dto : list) {
			String serverFolderPath = this.uploadpath + File.separator + "vehicle";
			//行驶证正面
			if (StrUtil.isNotEmpty(dto.getDrivingLicenseImg())) {
				//String driveringLicenseImg = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getDrivingLicenseImg(), serverFolderPath, dto.getVehicleNumber());
				String driveringLicenseImg = postDownloadEvent(dto.getDrivingLicenseImg(), serverFolderPath, dto.getVehicleNumber());
				//覆盖导入的长地址，启用网货平台对应的短地址,前面拼接vehicle目录
				dto.setDrivingLicenseImg("vehicle/" + driveringLicenseImg);
				Thread.sleep(300);
			}

			//行驶证反面
			if (StrUtil.isNotEmpty(dto.getDrivingLicenseImg2())) {
				//String driveringLicenseImg2 = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getDrivingLicenseImg2(), serverFolderPath, dto.getVehicleNumber());
				String driveringLicenseImg2 = postDownloadEvent(dto.getDrivingLicenseImg2(), serverFolderPath, dto.getVehicleNumber());
				dto.setDrivingLicenseImg2("vehicle/" + driveringLicenseImg2);
			}

			//道路运输证主页
			if (StrUtil.isNotEmpty(dto.getRoadTransportImg())) {
				//String roadTransportImg = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getRoadTransportImg(), serverFolderPath, dto.getVehicleNumber());
				String roadTransportImg = postDownloadEvent(dto.getRoadTransportImg(), serverFolderPath, dto.getVehicleNumber());
				dto.setRoadTransportImg("vehicle/" + roadTransportImg);
				Thread.sleep(300);
			}

			//挂车照片正面
			if (StrUtil.isNotEmpty(dto.getTrailerVehiclLicenseImg())) {
				//String trailerVehiclLicenseImg = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getTrailerVehiclLicenseImg(), serverFolderPath, dto.getVehicleNumber());
				String trailerVehiclLicenseImg = postDownloadEvent(dto.getTrailerVehiclLicenseImg(), serverFolderPath, dto.getVehicleNumber());
				dto.setTrailerVehiclLicenseImg("vehicle/" + trailerVehiclLicenseImg);
			}

			//挂车照片反面
			if (StrUtil.isNotEmpty(dto.getTrailerVehiclLicenseImg2())) {
				//String trailerVehiclLicenseImg2 = PhotoCrawlerUtil.downloadAbsolutePathPic(dto.getTrailerVehiclLicenseImg2(), serverFolderPath, dto.getVehicleNumber());
				String trailerVehiclLicenseImg2 = postDownloadEvent(dto.getTrailerVehiclLicenseImg2(), serverFolderPath, dto.getVehicleNumber());
				dto.setTrailerVehiclLicenseImg2("vehicle/" + trailerVehiclLicenseImg2);
				Thread.sleep(300);
			}

			//挂车道路运输证
			if (StrUtil.isNotEmpty(dto.getTrailerVehicleRoadTransportImg())) {
				String trailerVehicleRoadTransportImg = postDownloadEvent(dto.getTrailerVehicleRoadTransportImg(), serverFolderPath, dto.getVehicleNumber());
				dto.setTrailerVehicleRoadTransportImg("vehicle/" + trailerVehicleRoadTransportImg);
			}

			//人车合照
			if (StrUtil.isNotEmpty(dto.getVehicleImg())) {
				String vehicleImg = postDownloadEvent(dto.getVehicleImg(), serverFolderPath, dto.getVehicleNumber());
				dto.setVehicleImg("vehicle/" + vehicleImg);
			}

			log.info("正在下载{}图片 {}/{}", dto.getVehicleNumber(), index, list.size());
			index++;
		}

		hyVehicleService.saveBatchVehice(list);
		return Result.OK("文件导入成功！数据行数：" + list.size());
	}


	private String postDownloadEvent(String downloadUrl, String serverFolderPath, String serverFolderName) {

		this.applicationEventPublisher.publishEvent(PicDownloadEvent.builder()
				.type("vehicle")
				.downloadUrl(downloadUrl)
				.serverFolderPath(serverFolderPath)
				.serverFolderName(serverFolderName)
				.build()
		);

		int lastIndex = downloadUrl.lastIndexOf('/');
		String filename = downloadUrl.substring(lastIndex);

		return serverFolderName + File.separator + filename;
	}

	private  void checkData(List<ImportHyVehiceDTO> list){
		int i = 2;
		for(ImportHyVehiceDTO importHyVehiceDTO :list){
			String key = String.valueOf(i);

			if (StringUtils.isBlank(importHyVehiceDTO.getVehicleNumber())) {
				throw new JeecgBootException("第"+ key+ "行车辆牌照号不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getVehiclePlateColorCode())) {
				throw new JeecgBootException("第"+ key+ "行车牌颜色不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getVehicleType())) {
				throw new JeecgBootException("第"+ key+ "行车辆类型不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getOwner())) {
				throw new JeecgBootException("第"+ key+ "行所有人不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getVin())) {
				throw new JeecgBootException("第"+ key+ "行车辆识别代号不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getIssuingOrganizations())) {
				throw new JeecgBootException("第"+ key+ "行发证机关不能为空,请先补充信息");
			}

			if (StringUtils.isBlank(importHyVehiceDTO.getVehicleEnergyType())) {
				throw new JeecgBootException("第"+ key+ "行车辆能源类型不能为空,请先补充信息");
			}
			if (importHyVehiceDTO.getVehicleTonnage() == null || importHyVehiceDTO.getVehicleTonnage().compareTo(BigDecimal.ZERO) == 0) {
				throw new JeecgBootException("第"+ key+ "行核定载质量不能为空,请先补充信息");
			}
			if (importHyVehiceDTO.getVehicleTonnage().compareTo(new BigDecimal("100")) > 0) {
				throw new JeecgBootException("第"+ key+ "行核定载质量超过100吨");
			}
			if (importHyVehiceDTO.getGrossMass() == null || importHyVehiceDTO.getGrossMass().compareTo(BigDecimal.ZERO) == 0) {
				throw new JeecgBootException("第"+ key+ "行吨位不能为空,请先补充信息");
			}
			if (importHyVehiceDTO.getGrossMass().compareTo(new BigDecimal("100")) > 0) {
				throw new JeecgBootException("第"+ key+ "行总吨位超过100吨");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getRoadTransportCertificateNumber())) {
				throw new JeecgBootException("第"+ key+ "行道路运输证号不能为空,请先补充信息");
			}
			if (StringUtils.isBlank(importHyVehiceDTO.getUseCharacter())) {
				throw new JeecgBootException("第"+ key+ "行使用性质不能为空,请先补充信息");
			}

			Date registerDate =  DateUtils.str2Date(importHyVehiceDTO.getRegisterDate(), DateUtils.date_sdf.get());
			Date issueDate =  DateUtils.str2Date(importHyVehiceDTO.getIssueDate(), DateUtils.date_sdf.get());

			if (registerDate == null) {
				throw new JeecgBootException("第"+ key+ "行注册日期不正确,应为日期文本格式");
			}
			if (issueDate == null) {
				throw new JeecgBootException("第"+ key+ "行发证日期不正确,应为日期文本格式");
			}
			i++;
		}


	}

	@ApiOperation(value="车辆管理-分页列表查询", notes="车辆管理-分页列表查询")
	@GetMapping(value = "/allList")
	public Result<?> allList(@RequestParam(name="keyword") String keyword) {
		QueryWrapper<HyVehicle> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("examine_status",ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
		if(StringUtils.isEmpty(keyword)){
			return Result.OK(null);
		}
		queryWrapper.like("vehicle_number", keyword);
		//如果是承运商的话，只能查自己的车辆
		if (userUtil.isCaptain()){
			queryWrapper.in("id",userUtil.getHyVehicleIdList());
		}
		List<HyVehicle> list = hyVehicleService.list(queryWrapper);
		return Result.OK(list);
	}

	@AutoLog(value = "APP车辆信息-司机车辆绑定")
	@ApiOperation(value="APP车辆信息-司机车辆绑定",httpMethod = "POST", notes="APP车辆信息-司机车辆绑定")
	@PutMapping(value = "/binding")
	public Result<?> binding(@RequestBody JSONObject jsonObject) {
		String vehicleId = jsonObject.getString("vehicleId");
		String driverId = jsonObject.getString("driverId");
		if (StringUtils.isEmpty(driverId)) {
			return Result.error("司机信息不能为空");
		}
		if (StringUtils.isEmpty(vehicleId)) {
			return Result.error("车辆信息不能为空");
		}
		HyDriver driver =  hyDriverService.getById(driverId);
		if(driver == null){
			return Result.error("您的司机信息不存在！");
		}
		HyVehicle hyVehicle  = hyVehicleService.getById(vehicleId);
		if(hyVehicle == null){
			return Result.error("您的车辆信息不存在！");
		}
		if(hyVehicleService.binding(driverId,vehicleId)){
			return Result.OK("绑定成功！");
		}
		return Result.error("绑定失败！");
	}


	@AutoLog(value = "后台智运宝设备车辆绑定")
	@ApiOperation(value="后台智运宝设备车辆绑定",httpMethod = "PUT", notes="后台智运宝设备车辆绑定")
	@PutMapping(value = "/zybBinding")
	public Result<?> zybBinding(@RequestBody HyVehicleReq hyVehicleReq) {

		if (StrUtil.isEmpty(hyVehicleReq.getVehicleNumber()) || StrUtil.isEmpty(hyVehicleReq.getVehicleDevice())) {
			return Result.error("车牌号或智运宝设备号不能为空");
		}

		return this.hyVehicleService.zybBinding(hyVehicleReq);
	}


	@AutoLog(value = "后台智运宝解绑")
	@ApiOperation(value="后台智运宝解绑",httpMethod = "PUT", notes="后台智运宝解绑")
	@PutMapping(value = "/zybUnbinding")
	public Result<?> zybUnbinding(@RequestBody HyVehicleReq hyVehicleReq) {

		if (StrUtil.isEmpty(hyVehicleReq.getVehicleNumber()) || StrUtil.isEmpty(hyVehicleReq.getVehicleDevice())) {
			return Result.error("车牌号或智运宝设备号不能为空");
		}

		return this.hyVehicleService.zybUnBinding(hyVehicleReq);
	}


	@ApiOperation(value="车辆管理-查询已绑定设备的车辆", notes="车辆管理-查询已绑定设备的车辆")
	@GetMapping(value = "/zyblist")
	public Result<?> queryZybList() {

		//如果当前智运宝设备已经指派在某个货源，不在列表中显示
		List<HyZybStatus> zybStatusList = this.hyZybService.list();
		List<String> deviceList = null;
		if (CollUtil.isNotEmpty(zybStatusList)) {
			deviceList = zybStatusList.stream().map(z->z.getVehicleDevice()).collect(Collectors.toList());
		}

//		List<HyVehicle> hyVehicleList = this.hyVehicleService.list(new LambdaQueryWrapper<HyVehicle>()
//				.isNotNull(HyVehicle::getVehicleDevice)
//				.notIn(CollUtil.isNotEmpty(deviceList), HyVehicle::getVehicleDevice, deviceList)
//				.eq(HyVehicle::getExamineStatus, ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode()));

		List<HyVehicle> hyVehicleList = this.hyVehicleService.list(new LambdaQueryWrapper<HyVehicle>()
				.isNotNull(HyVehicle::getVehicleDevice)
				.eq(HyVehicle::getExamineStatus, ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode()));

		return Result.OK(hyVehicleList);
	}

	@AutoLog(value = "APP车辆信息-司机车辆-批量绑定")
	@ApiOperation(value="APP车辆信息-司机车辆-批量绑定",httpMethod = "POST", notes="APP车辆信息--司机车辆-批量绑定")
	@PutMapping(value = "/bindingbatch")
	public Result<?> bindingbatch(@RequestBody JSONObject jsonObject) {
		String vehicleIdString = jsonObject.getString("vehicleIds");
		String driverId = jsonObject.getString("driverId");
		if (StringUtils.isEmpty(driverId)) {
			return Result.error("司机信息不能为空");
		}
		if (StringUtils.isEmpty(vehicleIdString)) {
			return Result.error("车辆信息不能为空");
		}
		HyDriver driver =  hyDriverService.getById(driverId);
		if(driver == null){
			return Result.error("您的司机信息不存在！");
		}
		List <String> idStrings =  Arrays.asList(vehicleIdString.split(","));
		for(String vehicleId: idStrings){
			hyVehicleService.binding(driverId,vehicleId);
		}
		return Result.OK("绑定成功！");
	}


	@AutoLog(value = "APP车辆信息-司机解绑车辆")
	@ApiOperation(value="APP车辆信息-司机解绑车辆",httpMethod = "POST", notes="APP车辆信息-司机解绑车辆")
	@PutMapping(value = "/unbundlingVehiclet")
	public Result<?> unbundlingVehiclet(@RequestBody JSONObject jsonObject) {
		String vehicleId = jsonObject.getString("vehicleId");
		String driverId = jsonObject.getString("driverId");
		if (StringUtils.isEmpty(driverId)) {
			return Result.error("司机信息不能为空");
		}
		if (StringUtils.isEmpty(vehicleId)) {
			return Result.error("车辆信息不能为空");
		}

		HyDriver driver =  hyDriverService.getById(driverId);
		if(driver == null){
			return Result.error("您的司机信息不存在！");
		}
		HyVehicle hyVehicle  = hyVehicleService.getById(vehicleId);
		if(hyVehicle == null){
			return Result.error("您的车辆信息不存在！");
		}
		HyDriverVehicle hyDriverVehicle = hyDriverVehicleService.getInfoByDriverIdAndVehicleId(
				driver.getId(),vehicleId);
		if(hyDriverVehicle==null){
			return Result.error("解绑失败，您的车辆信息未绑定！");
		}
		LoginUser user = UserUtil.getLoginUser();
		hyDriverVehicle.setIzUsed(0);
		hyDriverVehicle.setUpdateBy(user.getUsername());
		hyDriverVehicle.setUpdateTime(new Date());
		if(!hyDriverVehicleService.updateById(hyDriverVehicle)){
			return Result.error("解绑失败！");
		}

		//如果解绑成功，清除车辆表中的司机ID
		this.hyVehicleService.update(new LambdaUpdateWrapper<HyVehicle>()
						.eq(HyVehicle::getId, vehicleId)
						.set(HyVehicle::getDriverId, StringUtils.EMPTY));

		return Result.OK("解绑成功！");
	}


	@AutoLog(value = "交科院系统补上传挂车")
	@ApiOperation(value="交科院系统补上传挂车",httpMethod = "POST", notes="交科院系统补上传挂车")
	@PostMapping(value = "/uploadTrailerVehicle")
	public Result<?> uploadTrailerVehicle(@RequestBody JSONObject jsonObject) {
		return this.nmgReportService.uploadTrailerVehicle(jsonObject);
	}

	/**
	 * 获取待审车辆数
	 * @return
	 */
	@GetMapping(value = "/getDsVehicle")
	public Result<?> getDsVehicle() {
		int count = hyVehicleService.getDsvehicleCount(userUtil.getCustomerById());
		return Result.OK(count);
	}


	/**
	 * 订阅车辆
	 */
	@AutoLog(value = "加入运力池-订阅车辆")
	@ApiOperation(value = "加入运力池-订阅车辆", notes = "加入运力池-订阅车辆")
	@GetMapping(value = "/subscribeToVehicles")
	public Result<?> subscribeToVehicles(@RequestParam(name = "id", required = true) String id) {
		HyVehicle hyVehicle = this.hyVehicleService.getById(id);
		if (null == hyVehicle) {
			return Result.error("车辆信息获取错误！");
		}

		if (!this.hyVehicleService.update(new LambdaUpdateWrapper<HyVehicle>()
				.eq(HyVehicle::getId, id)
				.set(HyVehicle::getTransCapacity, 1))) {
			return Result.error("订阅车辆失败");
		}

		return Result.OK("订阅车辆成功");
	}


	@AutoLog(value = "取消运力池-订阅车辆")
	@ApiOperation(value = "取消运力池-订阅车辆", notes = "取消运力池-订阅车辆")
	@GetMapping(value = "/unsubscribeToVehicles")
	public Result<?> unsubscribeToVehicles(@RequestParam(name = "id", required = true) String id) {
		HyVehicle hyVehicle = this.hyVehicleService.getById(id);
		if (null == hyVehicle) {
			return Result.error("车辆信息获取错误！");
		}

		if (!this.hyVehicleService.update(new LambdaUpdateWrapper<HyVehicle>()
				.eq(HyVehicle::getId, id)
				.set(HyVehicle::getTransCapacity, 0))) {
			return Result.error("取消订阅车辆失败");
		}

		return Result.OK("取消订阅车辆成功");
	}
	@ApiOperation(value="车辆管理-分页列表查询", notes="车辆管理-分页列表查询")
	@GetMapping(value = "/allList2")
	public Result<?> allList2(@RequestParam(name="keyword") String keyword) {
		QueryWrapper<HyVehicle> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("examine_status",ExamineStatusEnum.EXAMINE_STATUS_APPROVED.getCode());
		if(StringUtils.isEmpty(keyword)){
			return Result.OK(null);
		}
		queryWrapper.like("vehicle_number", keyword);
		List<HyVehicle> list = hyVehicleService.list(queryWrapper);
		return Result.OK(list);
	}


}
